#!/usr/bin/env python
#-*-coding:utf-8-*-
# @author adu
# @date 2016-09-17

from client import WebClient

from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr,formataddr
import smtplib

import json
import time
import configparser
import re
import os

#模拟的客户端
wc = WebClient()
#邮箱所需全局变量
from_addr = ''
password = ''
smtm_server = 'smtp.163.com'
#邮件内容数组
text_arr = []
#存放读取到的配置内容
train_config = {}
email_config = {}
#config最后修改时间
config_mtime = 0

def load_config():
	global train_config
	global email_config
	global from_addr
	global password
	config = configparser.ConfigParser()
	try:
		config.read('config.ini',encoding='UTF-8')
		train_config = config['train']
		email_config = config['email']
		from_addr = email_config['server_email']
		password = email_config['server_password']
		convert_station()
	except Exception:
		raise

def do_send_email(msg, to_addr=[]):
	try:
		mime_text = MIMEText(msg,"html","utf-8")
		mime_text['From'] = from_addr
		mime_text['To'] = ','.join(to_addr)
		mime_text['Subject'] = Header(u'火车票监控程序','utf-8').encode()
		server = smtplib.SMTP(smtm_server,port=25)
		server.set_debuglevel(1)
		server.login(from_addr, password)
		server.sendmail(from_addr, to_addr, mime_text.as_string())
		print(u'send successfully!')
	except Exception:
		raise
	finally:
		server.quit()

def convert_station():
	url = "https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.8966"
	resp = wc.do_get(url)
	stations = re.findall(r'@[a-z]+\|(.*?)\|([A-Z]+)\|.*?\d+', resp)
	station_codes = dict(stations)
	from_station = station_codes[train_config['from_station']]
	to_station = station_codes[train_config['to_station']]
	train_config['from_station'] = from_station
	train_config['to_station'] = to_station

def query_with_param(qdate,from_station,to_station):
	url = u"https://kyfw.12306.cn/otn/leftTicket/queryT?leftTicketDTO.train_date=%s&leftTicketDTO.from_station=%s&leftTicketDTO.to_station=%s&purpose_codes=ADULT" % (qdate,from_station,to_station)
	try:
		resp = wc.do_get(url)
		resp_json = json.loads(resp)
		data_json = resp_json['data']
		for data in data_json:
			train_info = data['queryLeftNewDTO']
			can_buy = train_info['canWebBuy']
			#如果有票
			if can_buy == 'Y' and check_train_info(train_info):
				train_code = train_info['station_train_code']
				start_time = train_info['start_time']
				arrive_time = train_info['arrive_time']
				yz_num = train_info['yz_num']
				yw_num = train_info['yw_num']
				rz_num = train_info['rz_num']
				wz_num = train_info['wz_num']
				station = "%s -> %s" % (train_info['from_station_name'],train_info['to_station_name'])
				text_arr.append(
					"<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>" 
						% (station,qdate,train_code,start_time,arrive_time,rz_num,yw_num,yz_num,wz_num))
	except Exception:
		raise

def query():
	query_date = train_config['query_date']
	qdate_arr = query_date.split(',')
	for qdate in qdate_arr:
		query_with_param(qdate,train_config['from_station'],train_config['to_station'])
	global text_arr
	train_text = ''.join(text_arr)
	if len(text_arr) > 0:
		send_email(train_text)
	text_arr = []

def send_email(train_text):
	with open("template.html","rt",encoding="utf-8",errors="ignore") as f:
		data = f.read()
		data = data.replace("@@train_text@@",train_text)
		to_addr = email_config['to_email'].split(',')
		do_send_email(data, to_addr)

def check_train_info(train_info):
	train_stime_str = train_info['start_time']
	train_stime = time.strptime(train_stime_str,'%H:%M')
	query_time_arr = train_config['query_time'].split(',')
	flag = False
	#检测是否在配置的时间段内
	for query_time in query_time_arr:
		ftime_str = query_time.split('-')[0]
		ttime_str = query_time.split('-')[1]
		ftime = time.strptime(ftime_str,'%H:%M')
		ttime = time.strptime(ttime_str,'%H:%M')
		fminute = ftime.tm_hour * 60 + ftime.tm_min
		tminute = ttime.tm_hour * 60 + ftime.tm_min
		train_sminute = train_stime.tm_hour * 60 + train_stime.tm_min
		if fminute <= train_sminute and train_sminute <= tminute:
			flag = True
			break
	if flag:
		station_code = train_info['station_train_code'].lower()[0]
		monitor_codes = train_config['station_code'].lower().split(',')
		if len(monitor_codes) > 0:
			if station_code not in monitor_codes:
				flag = False

	if flag:
		flag = False
		#检测是否有硬座或者硬卧
		if train_info['yz_num'] != '--' and train_info['yz_num'] != '无':
			flag = True
		if train_info['rz_num'] != '--' and train_info['rz_num'] != '无':
			flag = True
		if train_info['yw_num'] != '--' and train_info['yw_num'] != '无':
			flag = True
	return flag

def reload_config():
	global config_mtime
	mtime = int(os.stat('config.ini').st_mtime)
	if mtime > config_mtime:
		load_config()
		config_mtime = mtime

def main():
	while True:
		try:
			reload_config()#加载配置文件
			interval = int(train_config['interval'])
			lm = time.localtime()
			if lm.tm_hour > 6 and lm.tm_hour < 23:
				query()
				time.sleep(interval)
			else:
				time.sleep(60 * 60)
		except Exception as e:
			print(e)
 
if __name__ == '__main__':
	#main()
	reload_config()#加载配置文件
	query()
	print(text_arr)
	